<template>
	<el-form ref="form" size="medium" :model="letterForm" :rules="letterRules" label-width="80px" class="send_letter_form">
		<el-form-item label="私信标题" prop="title">
			<el-input v-model="letterForm.title"></el-input>
		</el-form-item>
		<el-form-item label="收件人" prop="receivePerson">
			<consignee v-model="letterForm.receivePerson"></consignee>
		</el-form-item>
		<el-form-item label="私信内容" prop="content">
			<sw-tiny-editor v-model="letterForm.content" type="custom" height="400"></sw-tiny-editor>
		</el-form-item>
		<el-form-item>
			<el-button v-bind="submitConfig" :loading="btnLoading" @click="handleSendLetter()">发送</el-button>
			<el-button size="medium" @click="handleCancelSend()">取消发送</el-button>
		</el-form-item>
	</el-form>
</template>

<script>
import consignee from './consignee';
import { addNotice } from '@/api/front/sysNotice';
export default {
	components: { consignee },
	props: {
		value: { type: Boolean, default: false }
	},
	data() {
		return {
			visible: this.value,
			letterForm: {},
			letterRules: {
				title: [{ required: true, message: '请输入私信标题', trigger: 'blur' }],
				receivePerson: [{ required: true, message: '请选择收件人', trigger: 'change' }],
				content: [{ required: true, message: '请输入私信内容', trigger: 'blur' }]
			},
			btnLoading: false,
			submitConfig: {
				size: 'medium',
				type: 'primary',
				icon: 'el-icon-s-promotion'
			}
		};
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) {
				this.$refs['form'].resetFields();
				this.letterForm = {};
			}
		}
	},
	mounted() {},
	methods: {
		//发送私信
		handleSendLetter() {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				this.sendLetterRequest();
			});
		},

		//取消发送
		handleCancelSend() {
			this.$router.go(-1);
		},

		//私信参数格式化
		formatLetterParams() {
			let params = { ...this.letterForm, type: 2 };
			params['receivePerson'] = params.receivePerson.map((n) => n.id);
			return params;
		},

		//发送私信请求
		async sendLetterRequest() {
			let params = this.formatLetterParams();
			let result = await addNotice(params).then((res) => res.data);
			this.btnLoading = false;
			if (result.code === '0') {
				this.$message.success('发送成功');
				this.visible = false;
				this.$router.back();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.send_letter_form {
	padding: 22px 22px 0;
}
.send_letter_left {
	display: flex;
	flex-direction: column;
	flex: 1;
	padding: 16px;
	overflow: hidden;
}
.send_letter_right {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	width: 20%;
	padding: 16px;
	flex-shrink: 0;
	min-width: 320px;
	border-left: solid 1px #e4e7ed;
}
</style>
